package GUI;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import Core.Connection;

public class ConnectMenu extends AbstractMenu
{
	private JTextField serverAddr;
	private JTextField serverPort;
	private JLabel label;
	private JButton button;
	private JLabel logo;
	public ConnectMenu(JFrame frame) 
	{
		super(frame);
		this.getFrame().getContentPane().setBackground(new Color(125, 184, 255));
		
		logo = new JLabel(new ImageIcon("logo.png"));
		logo.setBounds(220,10,300,100);
		
		
		label = new JLabel("Interactive Forums");
		label.setBounds(315,70,400,30);
		label.setFont(new Font(label.getFont().getName(),label.getFont().getStyle(), 30));
		label.setForeground(new Color(0,0,0));
		
		serverAddr = new JTextField("localhost");
		serverAddr.setBounds(300, 260, 120, 25);
		serverAddr.setFont(new Font(label.getFont().getName(),label.getFont().getStyle(), 15));
		
		serverPort = new JTextField("8001");
		serverPort.setBounds(430, 260, 70, 25);
		serverPort.setFont(new Font(label.getFont().getName(),label.getFont().getStyle(), 15));
		
		
		button = new JButton("Connect to server");
		button.setBounds(300, 300, 200, 30);
		button.addActionListener(new ActionListener() 
									{
							            public void actionPerformed(ActionEvent e)
							            {
							            	String target = serverAddr.getText();
							            	String port = serverPort.getText();
							            	int port_i=80;
							            	try
							            	{
							            		port_i = Integer.parseInt(port);
							            	}
							            	catch(Exception ex)
							            	{
							            		JOptionPane.showMessageDialog(null, "Invalid port", "Connection Error", JOptionPane.ERROR_MESSAGE);
							            		return;
							            	}
							            	boolean connect = Connection.connect(target, port_i);
							                if(!connect)
							                {
							                	JOptionPane.showMessageDialog(null, "Could not establish connection", "Connection Error", JOptionPane.ERROR_MESSAGE);
							                	return;
							                }
							                MainWindow.switchMenu(new LobbyMenu(getFrame()));
							            }
									}
								);
		
	}
	
	public void create()
	{
		regItem(label);
		regItem(serverAddr);
		regItem(serverPort);
		regItem(button);
		regItem(logo);
		getFrame().repaint();
	}
	
	public void connectionInterrupted() 
	{
		// TODO Auto-generated method stub
		
	}

	public void incomingMessage(String msg) 
	{
		// TODO Auto-generated method stub
		
	}
}